package com.caocaog.market.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caocaog.market.annotation.IgnoreAuth;
import com.caocaog.market.entity.Member;
import com.caocaog.market.entity.MemberAddress;
import com.caocaog.market.service.IMemberAddressService;
import com.caocaog.market.service.MemberService;
import com.caocaog.market.util.BytedanceMicroApp;
import com.caocaog.market.util.WxUtil;
import com.caocaog.market.vo.MemberVO;
import com.caocaog.market.vo.WxMiniBO;
import com.caocaog.market.vo.WxPhoneVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.bdPay.ByteDanceUrlConstants;
import org.jeecg.common.bdPay.RestTemplateUtil;
import org.jeecg.common.exception.CheckFailedException;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * API用户
 *
 * @author yuki guo
 * Date 2021/12/14 9:48 上午
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(value = "memberApi", tags = "API用户")
@RequestMapping("/api/member")
public class ApiMemberController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private IMemberAddressService memberAddressService;
    @Autowired
    private RestTemplateUtil restTemplateUtil;


    @IgnoreAuth
    @ApiOperation(value = "获取openId", response = WxPhoneVO.class)
    @PostMapping("/getOpenId")
    public Result getOpenId(@RequestBody WxMiniBO wxMiniBO) {

        WxPhoneVO wxPhoneVO = WxUtil.getUserInfo(wxMiniBO);
        Member member = memberService.getOne(new QueryWrapper<Member>().eq("wx_openid", wxPhoneVO.getOpenId()));
        MemberVO vo = new MemberVO();
        if (null != member) {
            BeanUtils.copyProperties(member, vo);
            wxPhoneVO.setMemberVO(vo);
            String appSign = JwtUtil.appSign(member.getId());
            wxPhoneVO.setToken(appSign);
            if (oConvertUtils.isEmpty(member.getWxUnionid())) {
                member.setWxUnionid(wxPhoneVO.getUnionId());
                memberService.updateById(member);
            }
        }

        return Result.OK("获取成功", wxPhoneVO);
    }

    @Value("${tiktok.app-id}")
    private String appid;
    @Value("${tiktok.secret}")
    private String secret;

    @ResponseBody
    @ApiOperation(value = "抖音小程序code2Session")
    @PostMapping("/bdLogin")
    public Result loginBind(@RequestBody JSONObject jsonObject) {
        String code = jsonObject.getString("code");
        if (null == code) {
            throw new CheckFailedException("code丢失");
        }
        JSONObject requestParameter = new JSONObject();
        requestParameter.put("code", code);
        requestParameter.put("appid", appid);
        requestParameter.put("secret", secret);
        log.info(requestParameter.toString());
        String resultString = restTemplateUtil.byteDancePostRequest(requestParameter, ByteDanceUrlConstants.CODE_2_SESSION);
        JSONObject resultJson = JSON.parseObject(resultString);
        log.info(resultString);
        if (resultJson.containsKey("err_no")) {
            BytedanceMicroApp.ErrCodeEnum errCodeEnum = BytedanceMicroApp.ErrCodeEnum.match(resultJson.getInteger("err_no"));
            if (errCodeEnum.err_no != 0)
                throw new JeecgBootException(errCodeEnum.err_tips);
        }
        BytedanceMicroApp.BytedanceMicroAppResult bytedanceMicroAppResult = resultJson.getObject("data", BytedanceMicroApp.BytedanceMicroAppResult.class);
        log.info(bytedanceMicroAppResult.toString());
        WxPhoneVO wxPhoneVO = new WxPhoneVO();
        wxPhoneVO.setUnionId(bytedanceMicroAppResult.getUnionid());
        wxPhoneVO.setOpenId(bytedanceMicroAppResult.getOpenid());
        wxPhoneVO.setSessionKey(bytedanceMicroAppResult.getSession_key());
        Member member = memberService.getOne(new QueryWrapper<Member>().eq("wx_openid", bytedanceMicroAppResult.getOpenid()));
        MemberVO vo = new MemberVO();
        if (null != member) {
            BeanUtils.copyProperties(member, vo);
            wxPhoneVO.setMemberVO(vo);
            String appSign = JwtUtil.appSign(member.getId());
            wxPhoneVO.setToken(appSign);
            if (oConvertUtils.isEmpty(member.getWxUnionid())) {
                member.setWxUnionid(wxPhoneVO.getUnionId());
                memberService.updateById(member);
            }
        }

        return Result.OK("获取成功", wxPhoneVO);
    }

    /**
     * 登录授权方法
     *
     * @param member 登录信息R     * @return 结果
     */
    @IgnoreAuth
    @PostMapping("/login")
    @ApiOperation(value = "登录授权方法", response = Member.class)
    public Result login(@RequestBody Member member) {
        return memberService.login(member);
    }

    /**
     * 获取用户的地址列表
     *
     * @param memberId
     * @return
     */
    @AutoLog(value = "获取用户的地址列表")
    @ApiOperation(value = "获取用户的地址列表", notes = "params: memberId")
    @GetMapping(value = "/getUserAddresses")
    public Result<?> getUserAddresses(@RequestParam("memberId") String memberId) {
        List<MemberAddress> memberAddressList = memberAddressService.getUserAddresses(memberId);
        return Result.OK(memberAddressList);
    }

    private static final String BY_ID = "会员信息-通过id查询";

    @AutoLog(value = BY_ID)
    @ApiOperation(value = BY_ID)
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id") String id) {
        return Result.OK(memberService.queryMemberOneById(id));
    }

    /**
     * 添加
     *
     * @param memberAddress
     * @return
     */
    @AutoLog(value = "用户地址管理表-添加")
    @ApiOperation(value = "用户地址管理表-添加", notes = "用户地址管理表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MemberAddress memberAddress) {
        memberAddressService.save(memberAddress);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param memberAddress
     * @return
     */
    @AutoLog(value = "用户地址管理表-编辑")
    @ApiOperation(value = "用户地址管理表-编辑", notes = "用户地址管理表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MemberAddress memberAddress) {
        memberAddressService.updateById(memberAddress);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户地址管理表-通过id删除")
    @ApiOperation(value = "用户地址管理表-通过id删除", notes = "用户地址管理表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        memberAddressService.removeById(id);
        return Result.OK("删除成功!");
    }

}
